 <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农网农产品价格实时监控</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .dashboard-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            margin: 20px;
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }
        .header h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .header p {
            font-size: 1.1rem;
            color: #7f8c8d;
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .stats-card h3 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 5px;
        }
        .stats-card p {
            margin: 0;
            opacity: 0.9;
        }
        .price-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border-left: 5px solid #667eea;
            transition: transform 0.2s;
        }
        .price-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .product-name {
            font-size: 1.2rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 10px;
        }
        .price-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #e74c3c;
        }
        .price-unit {
            font-size: 1rem;
            color: #7f8c8d;
        }
        .location {
            color: #3498db;
            font-weight: 500;
        }
        .timestamp {
            color: #95a5a6;
            font-size: 0.9rem;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-connected {
            background-color: #27ae60;
        }
        .status-disconnected {
            background-color: #e74c3c;
        }
        .refresh-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 25px;
            padding: 10px 25px;
            color: white;
            font-weight: 600;
            transition: all 0.3s;
        }
        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .loading {
            text-align: center;
            padding: 50px;
            color: #7f8c8d;
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .table-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
        .auto-refresh {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <!-- 头部 -->
        <div class="header">
            <h1><i class="bi bi-graph-up"></i> 惠农网农产品价格实时监控</h1>
            <p>实时监控全国农产品价格行情，数据来源于惠农网</p>
        </div>

        <!-- 状态栏 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="totalProducts">-</h3>
                    <p>监控产品数</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="totalRecords">-</h3>
                    <p>总记录数</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="recentRecords">-</h3>
                    <p>24小时新增</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="avgPrice">-</h3>
                    <p>平均价格(元/斤)</p>
                </div>
            </div>
        </div>

        <!-- 连接状态 -->
        <div class="auto-refresh">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <span class="status-indicator" id="redisStatus"></span>
                    <span id="statusText">检查连接状态...</span>
                </div>
            </div>
        </div>

        <!-- 分类标签 -->
        <ul class="nav nav-tabs mb-3" id="categoryTabs">
            <li class="nav-item"><a class="nav-link active" data-category="水果" href="#">水果</a></li>
            <li class="nav-item"><a class="nav-link" data-category="菌类" href="#">菌类</a></li>
            <li class="nav-item"><a class="nav-link" data-category="蔬菜" href="#">蔬菜</a></li>
            <li class="nav-item"><a class="nav-link" data-category="粮食" href="#">粮食</a></li>
            <li class="nav-item"><a class="nav-link" data-category="其它" href="#">其它</a></li>
        </ul>

        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <h4><i class="bi bi-bar-chart"></i> 产品价格分布</h4>
                    <canvas id="priceChart"></canvas>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h4><i class="bi bi-pie-chart"></i> 产品数据量占比</h4>
                    <canvas id="productChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 最新价格数据 -->
        <div class="table-container">
            <h4><i class="bi bi-list-ul"></i> 最新价格数据</h4>
            <div id="priceData">
                <div class="loading">
                    <i class="bi bi-hourglass-split"></i> 正在加载数据...
                </div>
            </div>
        </div>

        <!-- 产品统计表格 -->
        <div class="table-container">
            <h4><i class="bi bi-table"></i> 产品统计信息</h4>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>产品名称</th>
                            <th>最新价格</th>
                            <th>平均价格</th>
                            <th>价格区间</th>
                            <th>产地数量</th>
                            <th>数据量</th>
                        </tr>
                    </thead>
                    <tbody id="productTable">
                        <tr>
                            <td colspan="6" class="text-center">正在加载...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let priceChart, productChart;
        let autoRefreshInterval;
        let allProducts = [];
        let allPriceData = [];
        let currentCategory = '水果';
        // 分类与产品名映射（示例，实际可根据数据调整）
        const CATEGORY_MAP = {
            '水果': ['苹果', '香蕉', '葡萄', '西瓜', '橙子', '荔枝', '柚子', '芒果', '草莓', '菠萝', '龙眼', '猕猴桃', '杨梅', '柠檬', '甘蔗', '火龙果', '榴莲', '木瓜', '莲雾', '山竹', '杨桃', '金桔', '柑橘', '柚', '柿子', '李子', '杏', '樱桃', '无花果', '百香果', '石榴', '枇杷', '葡萄柚'],
            '菌类': ['鹿茸菇', '元蘑', '松树菌', '香菇', '平菇', '金针菇', '杏鲍菇', '鸡腿菇', '茶树菇', '猴头菇', '竹荪', '牛肝菌', '白玉菇', '姬松茸'],
            '蔬菜': ['白菜', '西红柿', '黄瓜', '辣椒', '土豆', '茄子', '胡萝卜', '生菜', '菠菜', '芹菜', '青菜', '油麦菜', '莴苣', '南瓜', '冬瓜', '苦瓜', '丝瓜', '豆角', '豇豆', '四季豆', '毛豆', '豌豆', '萝卜', '大葱', '洋葱', '蒜苗', '大蒜', '姜', '香菜', '韭菜', '菜花', '西兰花', '花椰菜', '空心菜', '莴笋', '竹笋', '芦笋', '藕', '山药', '紫薯', '红薯', '地瓜', '莴苣', '莴笋', '苋菜', '茼蒿', '香椿'],
            '粮食': ['大米', '小麦', '玉米', '高粱', '大豆', '黑豆', '绿豆', '小米', '糯米', '荞麦', '燕麦', '红豆', '豌豆', '面粉', '芝麻', '花生', '豆类', '豆粕', '豆油', '豆皮', '豆腐', '豆浆', '豆芽', '豆角', '豇豆', '四季豆', '毛豆', '豌豆', '豌豆黄', '豌豆粉', '豌豆苗', '豌豆尖', '豌豆叶', '豌豆花', '豌豆梗', '豌豆茎', '豌豆根', '豌豆藤', '豌豆秧', '豌豆茎叶', '豌豆茎秧', '豌豆茎叶秧', '豌豆茎叶秧根', '豌豆茎叶秧根藤', '豌豆茎叶秧根藤花', '豌豆茎叶秧根藤花果', '豌豆茎叶秧根藤花果实', '豌豆茎叶秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗', '豌豆茎叶秧根藤花果实种子苗秧', '豌豆茎叶秧根藤花果实种子苗秧根', '豌豆茎叶秧根藤花果实种子苗秧根藤', '豌豆茎叶秧根藤花果实种子苗秧根藤花', '豌豆茎叶秧根藤花果实种子苗秧根藤花果', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实种子苗', '面粉', '玉米面', '小米', '大米', '糯米', '荞麦', '燕麦', '红豆', '黑豆', '绿豆', '芝麻', '花生', '豌豆', '豆类', '豆粕', '豆油', '豆皮', '豆腐', '豆浆', '豆芽', '豆角', '豇豆', '四季豆', '毛豆', '豌豆黄', '豌豆粉', '豌豆苗', '豌豆尖', '豌豆叶', '豌豆花', '豌豆梗', '豌豆茎', '豌豆根', '豌豆藤', '豌豆秧', '豌豆茎叶', '豌豆茎秧', '豌豆茎叶秧', '豌豆茎叶秧根', '豌豆茎叶秧根藤', '豌豆茎叶秧根藤花', '豌豆茎叶秧根藤花果', '豌豆茎叶秧根藤花果实', '豌豆茎叶秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗', '豌豆茎叶秧根藤花果实种子苗秧', '豌豆茎叶秧根藤花果实种子苗秧根', '豌豆茎叶秧根藤花果实种子苗秧根藤', '豌豆茎叶秧根藤花果实种子苗秧根藤花', '豌豆茎叶秧根藤花果实种子苗秧根藤花果', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实种子', '豌豆茎叶秧根藤花果实种子苗秧根藤花果实种子苗秧根藤花果实种子苗'],
            '其它': ['农产品']
        };

        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
            loadData();
            autoRefreshInterval = setInterval(loadData, 30000);
            // 分类标签点击事件
            document.querySelectorAll('#categoryTabs .nav-link').forEach(tab => {
                tab.addEventListener('click', function(e) {
                    e.preventDefault();
                    document.querySelectorAll('#categoryTabs .nav-link').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentCategory = this.getAttribute('data-category');
                    renderCategory();
                });
            });
        });

        // 初始化图表
        function initCharts() {
            // 价格分布图表
            const priceCtx = document.getElementById('priceChart').getContext('2d');
            priceChart = new Chart(priceCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: '平均价格 (元/斤)',
                        data: [],
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // 产品数据量图表
            const productCtx = document.getElementById('productChart').getContext('2d');
            productChart = new Chart(productCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: [
                            '#667eea', '#764ba2', '#f093fb', '#f5576c',
                            '#4facfe', '#00f2fe', '#43e97b', '#38f9d7'
                        ]
                    }]
                },
                options: {
                    responsive: true
                }
            });
        }

        // 加载数据
        async function loadData() {
            try {
                const priceResponse = await fetch('/api/latest_prices?limit=100');
                const priceData = await priceResponse.json();
                if (priceData.success) {
                    allPriceData = priceData.data;
                }
                const productsResponse = await fetch('/api/products');
                const productsData = await productsResponse.json();
                if (productsData.success) {
                    allProducts = productsData.products;
                }
                renderCategory();
                // 加载统计信息
                const statsResponse = await fetch('/api/statistics');
                const statsData = await statsResponse.json();

                if (statsData.success) {
                    updateStatistics(statsData);
                }

                // 检查健康状态
                const healthResponse = await fetch('/api/health');
                const healthData = await healthResponse.json();

                if (healthData.success) {
                    updateStatus(healthData.redis_status);
                }

            } catch (error) {
                console.error('加载数据失败:', error);
                updateStatus('error');
            }
        }

        // 动态分类：名字包含关键词也归入对应分类
        function getCategoryForProduct(name) {
            if (!name) return '其它';
            // 优先精确匹配
            for (const [cat, arr] of Object.entries(CATEGORY_MAP)) {
                if (cat !== '其它' && arr.includes(name)) return cat;
            }
            // 名字包含关键词也归入对应分类
            const fruitKeywords = CATEGORY_MAP['水果'];
            for (const kw of fruitKeywords) {
                if (name.includes(kw)) return '水果';
            }
            const fungusKeywords = CATEGORY_MAP['菌类'];
            for (const kw of fungusKeywords) {
                if (name.includes(kw)) return '菌类';
            }
            const vegKeywords = CATEGORY_MAP['蔬菜'];
            for (const kw of vegKeywords) {
                if (name.includes(kw)) return '蔬菜';
            }
            const grainKeywords = CATEGORY_MAP['粮食'];
            for (const kw of grainKeywords) {
                if (name.includes(kw)) return '粮食';
            }
            return '其它';
        }

        function renderCategory() {
            // 1. 过滤产品
            let filterNames = CATEGORY_MAP[currentCategory];
            let filteredProducts = allProducts.filter(p => getCategoryForProduct(p.name) === currentCategory).slice(0, 5);
            let filteredPriceData = allPriceData.filter(p => getCategoryForProduct(p.name) === currentCategory).slice(0, 20);
            // 2. 刷新卡片
            displayPriceData(filteredPriceData);
            // 3. 刷新表格
            updateProductTable(filteredProducts);
            // 4. 刷新图表
            updateCharts(filteredProducts);
        }

        // 显示价格数据
        function displayPriceData(data) {
            const container = document.getElementById('priceData');

            if (data.length === 0) {
                container.innerHTML = '<div class="text-center text-muted">暂无数据</div>';
                return;
            }

            const html = data.map(item => `
                <div class="price-card">
                    <div class="row align-items-center">
                        <div class="col-md-3">
                            <div class="product-name">${item.name}</div>
                        </div>
                        <div class="col-md-2">
                            <span class="price-value">${item.price_value}</span>
                            <span class="price-unit">元/${item.unit}</span>
                        </div>
                        <div class="col-md-3">
                            <span class="location"><i class="bi bi-geo-alt"></i> ${item.location}</span>
                        </div>
                        <div class="col-md-2">
                            <span class="timestamp">${formatTime(item.crawl_timestamp)}</span>
                        </div>
                        <div class="col-md-2">
                            <a href="${item.source_url}" target="_blank" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-box-arrow-up-right"></i> 查看
                            </a>
                        </div>
                    </div>
                </div>
            `).join('');

            container.innerHTML = html;
        }

        // 更新统计信息
        function updateStatistics(data) {
            const stats = data.statistics;
            const products = Object.keys(stats);

            document.getElementById('totalProducts').textContent = products.length;
            document.getElementById('totalRecords').textContent = Object.values(stats).reduce((sum, stat) => sum + stat.count, 0);
            document.getElementById('recentRecords').textContent = data.recent_count_24h;

            // 计算平均价格
            let totalPrice = 0;
            let totalCount = 0;
            Object.values(stats).forEach(stat => {
                totalPrice += stat.avg_price * stat.count;
                totalCount += stat.count;
            });
            const avgPrice = totalCount > 0 ? (totalPrice / totalCount).toFixed(2) : '0.00';
            document.getElementById('avgPrice').textContent = avgPrice;
        }

        // 更新产品表格
        function updateProductTable(products) {
            const tbody = document.getElementById('productTable');

            if (products.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
                return;
            }

            const html = products.map(product => `
                <tr>
                    <td><strong>${product.name}</strong></td>
                    <td><span class="text-danger fw-bold">${product.latest_price}</span> 元/斤</td>
                    <td>${product.avg_price} 元/斤</td>
                    <td>${product.price_range} 元/斤</td>
                    <td><span class="badge bg-info">${product.locations_count}</span></td>
                    <td><span class="badge bg-secondary">${product.data_count}</span></td>
                </tr>
            `).join('');

            tbody.innerHTML = html;
        }

        // 更新图表
        function updateCharts(products) {
            // 更新价格分布图表
            priceChart.data.labels = products.slice(0, 10).map(p => p.name);
            priceChart.data.datasets[0].data = products.slice(0, 10).map(p => p.avg_price);
            priceChart.update();

            // 更新产品数据量图表
            productChart.data.labels = products.slice(0, 8).map(p => p.name);
            productChart.data.datasets[0].data = products.slice(0, 8).map(p => p.data_count);
            productChart.update();
        }

        // 更新状态
        function updateStatus(status) {
            const statusIndicator = document.getElementById('redisStatus');
            const statusText = document.getElementById('statusText');

            statusIndicator.className = 'status-indicator';

            switch (status) {
                case 'connected':
                    statusIndicator.classList.add('status-connected');
                    statusText.textContent = 'Redis连接正常';
                    break;
                case 'disconnected':
                    statusIndicator.classList.add('status-disconnected');
                    statusText.textContent = 'Redis连接断开';
                    break;
                case 'error':
                    statusIndicator.classList.add('status-disconnected');
                    statusText.textContent = 'Redis连接错误';
                    break;
                default:
                    statusIndicator.classList.add('status-disconnected');
                    statusText.textContent = '检查连接状态...';
            }
        }

        // 格式化时间
        function formatTime(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }
    </script>
</body>
</html>